#include "tcpClient.hpp"
#include <iostream>

namespace client {
bool exit_flag = false;
boost::asio::io_context io_context_inst;
std::queue<csn::TaskPackage_ptr> pkg_recv_queue;
void io_context_run() { io_context_inst.run(); }
class taskClient : public tcpClient {
public:
  taskClient(char const *host, char const *port)
      : tcpClient(io_context_inst,
                  tcp::resolver(io_context_inst).resolve(host, port),
                  pkg_recv_queue) {}
  virtual void err_handler() {
    cout << "err_handler";
    exit_flag = true;
  }
};
} // namespace client

int main(int argc, char const *argv[]) {
  try {
    if (argc != 3) {
      std::cerr << "Usage: Client.exe <host> <port>\n";
      return 1;
    }
    client::taskClient c(argv[1], argv[2]);
    std::thread([&]() { client::io_context_run(); }).detach();
    std::thread([&]() { // 监视连接状态，断开时退出程序
      while (!client::exit_flag) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
      }
      exit(1);
    })
        .detach();
    std::cout << "waitting for connection..." << std::endl;
    while (!c.is_connected())
      ;
    // thread for receiving
    std::thread([&]() {
      while (1) {
        if (!client::pkg_recv_queue.empty()) {
          auto pkg = client::pkg_recv_queue.front();
          client::pkg_recv_queue.pop();
          pkg->getPayload();
          pkg->show_content();
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
      }
    }).detach();

    std::cout << "connected" << std::endl;
    string line;
    while (1) {
      cin >> line;
      // auto pkg = new csn::FileTaskPackage(0, 0, line);
      auto pkg = std::make_shared<csn::TaskPackage>(line);
      c.write(pkg);
    }
    c.close();
  } catch (std::exception &e) {
    std::cerr << "Exception: " << e.what() << "\n";
  }
  return 0;
}
